package com.rpay.admin.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.rpay.admin.util.SessionUtil;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.util.common.CommonUtils;
import com.rpay.common.vo.PcsResult;
import com.rpay.model.admin.RpayAdminModule;
import com.rpay.model.admin.RpayAdminRole;
import com.rpay.model.admin.RpayAdminRoleModule;
import com.rpay.model.admin.RpayAdminUserRole;
import com.rpay.service.admin.impl.ModuleServiceImpl;
import com.rpay.service.admin.impl.RoleModuleServiceImpl;
import com.rpay.service.admin.impl.SecRoleServiceImpl;
import com.rpay.service.admin.impl.SecUserRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 角色县官
 */
@RestController
@RequestMapping("/api/admin/role")
public class AdminRoleController {
    @Autowired
    private SecRoleServiceImpl secRoleServiceImpl;

    @Autowired
    private ModuleServiceImpl moduleServiceImpl;

    @Autowired
    private SecUserRoleServiceImpl userRoleServiceImpl;

    @Autowired
    private RoleModuleServiceImpl roleModuleServiceImpl;

    // todo
//    @Autowired
//    private CustomInvocationSecurityMetadataSourceService customInvocationSecurityMetadataSourceService;


    /**
     * 查询当前用户创建的角色列表
     *
     * @return 查询结果
     */
    @RequestMapping(value = "/roleList", method = RequestMethod.GET)
    public PcsResult listRole() {
        List<RpayAdminRole> secRoleList = secRoleServiceImpl.listRole(SessionUtil.getCurrentUser());
        return PcsResult.build(secRoleList);
//        return CommonUtils.buildOutput(true, secRoleList);
    }

    /**
     * 查询用户的权限列表
     *
     * @return 查询结果
     */
    @RequestMapping(value = "/permissionList", method = RequestMethod.GET)
    public PcsResult listPermission() {
        List<RpayAdminUserRole> secUserRoleList = userRoleServiceImpl.getRoleByUser(SessionUtil.getCurrentUser());
//        Map result = CommonUtils.buildFailMessage("查询失败");
        PcsResult pcsResult = new PcsResult("查询失败");
        if (!CommonUtils.isEmpty(secUserRoleList)) {
            Long roleId = secUserRoleList.get(0).getRoleId();
            pcsResult = ownPermission(roleId);
        }
        return pcsResult;
    }

    /**
     * 查询某个角色拥有的权限
     *
     * @param roleId 角色id
     * @return 查询结果
     */
    @RequestMapping(value = "/ownPermissions", method = RequestMethod.GET)
    public PcsResult ownPermission(Long roleId) {
        if (CommonUtils.isEmpty(roleId)) {
            return PcsResult.build(PcsResultCode.ERROR_OPERATE.getCode(), "角色id不能为空");
//            return CommonUtils.buildFailMessage("角色id不能为空");
        }
        RpayAdminRole secRole = new RpayAdminRole();
        secRole.setRoleId(roleId);
        List<RpayAdminModule> moduleList = moduleServiceImpl.findTModuleList(secRole);
        return PcsResult.build(moduleList);
//        return CommonUtils.buildOutput(true, moduleList);
    }

    /**
     * 新增角色
     *
     * @param role 角色
     * @return 新增结果
     */
    @RequestMapping(value = "/roleAdd", method = RequestMethod.POST)
    public PcsResult addRole(@RequestBody RpayAdminRole role) {
        if (CommonUtils.isEmpty(role)) {
            return PcsResult.build(PcsResultCode.PARAM_LOSE);
//            return CommonUtils.buildFailMessage("参数为空");
        }
        RpayAdminRole tempModel = new RpayAdminRole();
        tempModel.setRoleName(role.getRoleName());
        tempModel.setCreateUserId(SessionUtil.getUserId());
        RpayAdminRole model = secRoleServiceImpl.findRole(tempModel);
        if (!CommonUtils.isEmpty(model)) {
            return PcsResult.build(PcsResultCode.BUSINESS_ROLE_EXISTED);
//            return CommonUtils.buildFailMessage("该角色已存在");
        } else {
            role.setCreateUserId(SessionUtil.getUserId());
            secRoleServiceImpl.saveModel(role);
            return PcsResult.build(PcsResultCode.SUCCESS);
        }
    }

    /**
     * 编辑角色
     *
     * @param role 角色
     * @return 编辑结果
     */
    @RequestMapping(value = "/roleEdit", method = RequestMethod.PUT)
    public PcsResult editRole(@RequestBody RpayAdminRole role) {
        if (CommonUtils.isEmpty(role) || CommonUtils.isEmpty(role.getRoleId())) {
            return PcsResult.build(PcsResultCode.PARAM_INVALID);
//            return CommonUtils.buildFailMessage("参数为空");
        }
        RpayAdminRole tempModel = new RpayAdminRole();
        tempModel.setRoleName(role.getRoleName());
        tempModel.setCreateUserId(SessionUtil.getUserId());
        RpayAdminRole model = secRoleServiceImpl.findRole(tempModel);
        if (!CommonUtils.isEmpty(model)
                && model.getRoleId().longValue() != role.getRoleId().longValue()) {
            return PcsResult.build(PcsResultCode.BUSINESS_ROLE_EXISTED);
//            return CommonUtils.buildFailMessage("该角色名已存在");
        } else {
            secRoleServiceImpl.modModelByPrimaryKey(role);
            return PcsResult.build(PcsResultCode.SUCCESS);
//            return CommonUtils.buildSuccessMessage("修改成功");
        }
    }

    /**
     * 分页查询角色列表
     *
     * @param page     页码
     * @param pageSize 每页容量
     * @return 查询结果
     */
    @RequestMapping(value = "/rolesQuery", method = RequestMethod.GET)
    public PcsResult queryRoles(Integer page, Integer pageSize) {
        page = CommonUtils.isEmpty(page) ? 1 : page;
        pageSize = CommonUtils.isEmpty(pageSize) ? 10 : pageSize;
        RpayAdminRole secRole = new RpayAdminRole();

        PageInfo pageInfo = new PageInfo(secRoleServiceImpl.selectPage(secRole, page, pageSize));
        Map result = new HashMap();
        result.put("totalPage", pageInfo.getPages());
        result.put("totalRow", pageInfo.getTotal());
        result.put("roleList", pageInfo.getList());
        return PcsResult.build(result);
    }

    /**
     * 编辑角色权限（包含增删）
     *
     * @param role
     * @return
     */
    @RequestMapping(value = "/editPermissions")
    @Transactional
    public PcsResult editPermission(@RequestBody Map role) {
        if (CommonUtils.isEmpty(role) || CommonUtils.isEmpty(role.get("roleId"))) {
            return PcsResult.build(PcsResultCode.PARAM_INVALID);
//            return CommonUtils.buildFailMessage("参数错误");
        }
        long roleId = Long.parseLong(role.get("roleId").toString());
        //获取传递过来的module_id的集合
        JSONArray modules = JSONArray.parseArray(role.get("moduleId").toString());
        //存放所有module_id
        Set<Long> moduleIdSet = new HashSet();
        if (modules != null && modules.size() > 0) {
            RpayAdminModule parentModule;
            RpayAdminModule tempModel = new RpayAdminModule();
            //查询父级权限
            for (int i = 0; i < modules.size(); i++) {
                moduleIdSet.add(modules.getLong(i));
                tempModel.setModuleId(modules.getLong(i));
                parentModule = moduleServiceImpl.findParentModule(tempModel);
                while (parentModule != null) {
                    if (!moduleIdSet.contains(parentModule.getModuleId())) {
                        moduleIdSet.add(parentModule.getModuleId());
                    }
                    parentModule = moduleServiceImpl.findParentModule(parentModule);
                }
            }
        }

        RpayAdminRoleModule roleModule;
        List<RpayAdminRoleModule> roleModules = new ArrayList<>();
        for (Long moduleId : moduleIdSet) {
            roleModule = new RpayAdminRoleModule();
            roleModule.setModuleId(moduleId);
            roleModule.setRoleId(roleId);
            roleModules.add(roleModule);
        }

        //删除权限
        roleModuleServiceImpl.deleteBySql("deleteByRoleId", roleId);
        //新增权限
        // 暂时先循环更新  后期优化 批量更新 减少数据库压力
        // todo  增加批量更新
        if (roleModules != null && roleModules.size() > 0) {
            for (RpayAdminRoleModule roleModule1 : roleModules) {
                try {
                    roleModuleServiceImpl.saveModel(roleModule1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

//            roleModuleServiceImpl.saveModelList(roleModules);
        }
        //重新加载角色权限

        return PcsResult.build(PcsResultCode.SUCCESS);
    }
}
